const Router = require('koa-router');
const jwt = require('jsonwebtoken');
const util = require('util');
const verify = util.promisify(jwt.verify);
const decode = util.promisify(jwt.decode);
const query = require('../util/mysql');
const md5 = require('../util/md5');

const wrapper = require('../util/wrapper');
const checkError = require('../util/checkError');

const secret = {
  0: 'admin',
  1: 'customer',
};

const router = new Router();

router.prefix('/api/auth');

module.exports = router;

router.post('/check', async (ctx, next) => {
  const { type = 1 } = ctx.query;
  const token = ctx.request.headers.authorization;
  if (!token) {
    ctx.body = await wrapper(new Error('请求有误.'));
    return false;
  }

  const payload = await verify(token, secret[type]).catch(ex => {
    console.log(ex.message);
  });

  if (!payload) {
    ctx.body = wrapper(new Error('请登录'));
    return false;
  }

  const decode = jwt.decode(token, { complete: true });

  const { payload: { username } } = decode;

  const res = await query(`select id from user where username='${username}'`);

  if (checkError(res)) {
    ctx.body = await wrapper(new Error('服务异常.'));
    return false;
  }

  ctx.body = await wrapper({
    id: res[0] ? res[0].id : '',
    username,
  });
});

/**
 * 登录
 * @query type  区分0-管理员和1-用户
 */
router.post('/login', async (ctx, next) => {
  const { type = 1 } = ctx.query;
  const { username, password } = ctx.request.body;
  if (!username || !password) {
    ctx.body = await wrapper(new Error('请求有误.'));
    return false;
  }

  // 管理员
  if (+type === 0) {
    if (username === 'admin' && password === 'admin') {
      const token = jwt.sign({ username, }, secret[type], { expiresIn: '1h' });  //token签名 有效期为1小时
      ctx.body = wrapper({ token, });
    } else {
      ctx.body = wrapper(new Error('用户名或密码不正确'));
    }
  }
  // 用户
  else if (+type === 1) {
    const res = await query(`select id from user where username='${username}' and password='${md5(password)}'`);
    if (checkError(res)) {
      ctx.body = await wrapper(new Error('服务异常.'));
      return false;
    }
    if (res.length > 0) {
      const token = jwt.sign({ username, }, secret[type], { expiresIn: '1h' });  //token签名 有效期为1小时
      // 个人用户返回用户id
      ctx.body = wrapper({
        uid: res[0].id,
        token,
      });
    } else {
      ctx.body = wrapper(new Error('用户名或密码不正确'));
    }
  }
  else {
    ctx.body = await wrapper(new Error('缺少参数.'));
  }
});

/**
 * 用户注册
 */
router.post('/signup', async (ctx, next) => {
  const { type = 1 } = ctx.query;
  const { username, id_number, phone, password } = ctx.request.body;

  if (!username) {
    ctx.body = wrapper(new Error('请输入用户名'));
    return false;
  }

  if (!/^\d{17}(\d|X|x)$/img.test(id_number)) {
    ctx.body = wrapper(new Error('请输入正确的身份证号'));
    return false;
  }

  const ifExitNumber = await query(`select * from user where id_number=${id_number}`);
  if (ifExitNumber && ifExitNumber.length > 0) {
    ctx.body = wrapper(new Error('已经存在此身份证号'));
    return false;
  }

  if (!/^1\d{10}$/img.test(phone)) {
    ctx.body = wrapper(new Error('请输入正确的手机号'));
    return false;
  }

  const ifExitPhone = await query(`select * from user where phone=${phone}`);
  if (ifExitPhone && ifExitPhone.length > 0) {
    ctx.body = wrapper(new Error('已经存在此手机号'));
    return false;
  }

  if (!password) {
    ctx.body = wrapper(new Error('请输入不少于6位的字母和数字的组合作为密码'));
    return false;
  }

  const res = await query(`insert into user(username,phone,id_number,password,join_time) values('${username}','${phone}','${id_number}','${md5(password)}','${Date.now()}')`).catch(err => console.log(err));
  if (checkError(res)) {
    ctx.body = await wrapper(new Error('服务异常.'));
    return false;
  }

  const token = jwt.sign({ username, }, secret[type], { expiresIn: '1h' });  //token签名 有效期为1小时
  ctx.body = await wrapper({
    uid: res.insertId,
    token,
  });
});

/**
 * 获取用户投资信息
 */
router.get('/info/:uid', async (ctx, next) => {
  const { uid } = ctx.params;
  const token = ctx.request.headers.authorization;

  if (!uid) {
    ctx.body = await wrapper(new Error('缺少参数'));
    return false;
  }

  if (!token) {
    ctx.body = await wrapper(new Error('请求有误.'));
    return false;
  }

  // 判断是否登录
  const payload = await verify(token, secret[1]).catch(ex => {
    console.log(ex.message);
  });

  if (!payload) {
    ctx.body = wrapper(new Error('请登录'));
    return false;
  }

  const decode = jwt.decode(token, { complete: true });

  const { payload: { username } } = decode;

  const isSelf = await query(`select * from user where username='${username}' and id='${uid}'`);

  if (checkError(isSelf)) {
    ctx.body = await wrapper(new Error('服务异常.'));
    return false;
  }

  if (isSelf.length === 0) {
    ctx.body = await wrapper(new Error('只能查看本人信息.'));
    return false;
  }

  const res = await query(`select info from user where id=${uid}`);

  if (checkError(res)) {
    ctx.body = await wrapper(new Error('服务异常.'));
    return false;
  }

  ctx.body = await wrapper(res[0].info);

});
